import cv2
import numpy as np

# 绘制多边形
def drawShape(img, points):
    i = 0
    while i < len(points):
        if (i == len(points)-1):
            x, y = points[i][0]
            x1, y1 = points[0][0]
            print(x, y,x1, y1)
            cv2.line(img, (x, y), (x1, y1), (0, 0, 255), 3)
        else:
            x, y = points[i][0]
            x1, y1 = points[i+1][0]
            cv2.line(img, (x, y), (x1, y1), (0, 0, 255), 3)
        i = i + 1
# 读取图像
# img = cv2.imread('img/sz.jpg')
img = cv2.imread('img/hellow.jpg')

# 转换单通道图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化
ret,binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
# 查找轮廓
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓 轮廓红色 线宽1
cv2.drawContours(img, contours, -1, (0, 255, 0), 0)

# 计算面积
# area = cv2.contourArea(contours[0])
# print("area=", area)
# # 计算周长
# perimeter = cv2.arcLength(contours[0], True)
# print("perimeter=", perimeter)

# 多边形逼近   注意要找多个质点的图片
# e = 2
# approx = cv2.approxPolyDP(contours[0], e, True)
# print(len(approx))

# drawShape(img, approx)

# # 凸包
# hull = cv2.convexHull(contours[0])
# drawShape(img, hull)

# 最小外接矩形
r = cv2.minAreaRect(contours[1])
box = cv2.boxPoints(r)
box = np.int0(box)
cv2.drawContours(img, [box], 0, (0, 0, 255), 2)

# 最大外接矩形
rect = cv2.boundingRect(contours[1])
x, y, w, h = rect
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)



cv2.imshow('img', img)
cv2.waitKey(0)

